package cms.web.tag;

import cms.bean.template.Forum;
import cms.bean.template.TemplateRunObject;
import cms.manage.template.TemplateMain;
import cms.service.template.TemplateService;
import cms.utils.threadLocal.TemplateThreadLocal;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

import static cms.common.SystemConstant.InvokeMethod.INVOKE_CODE;
import static cms.common.SystemConstant.LayoutType.PUBLIC_REF_VALUE_PAGE;

/**
 * 模板自定义方法
 */
public class TemplateCustomMethods extends BaseTemplateMethods implements TemplateDirectiveModel {

    @Resource
    TemplateService templateService;
    @Resource
    TemplateMain templateMain;

    /**
     * @param env
     * @param params   参数
     * @param loopVars 循环变量
     * @param body     指令内容体
     */
    @Override
    public void doExecute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        String referenceCode = "";//版块引用代码

        TemplateRunObject templateRunObject = TemplateThreadLocal.get();
        List<String> layoutFile = new ArrayList<String>();//布局文件
        Map<String, Object> parameter = new HashMap<String, Object>();//提交参数
        Map<String, Object> runtimeParameter = new HashMap<String, Object>();//运行时参数

        //取得当前正在运行的引入指令
        if (templateRunObject != null) {
            referenceCode = templateRunObject.getReferenceCode();//引用代码
            layoutFile.addAll(templateRunObject.getLayoutFileList());//布局文件
            if (MapUtils.isNotEmpty(templateRunObject.getParameter())) {
                parameter.putAll(templateRunObject.getParameter());
                templateRunObject.getParameter().clear();
            }

            if (MapUtils.isNotEmpty(templateRunObject.getRuntimeParameter())) {
                runtimeParameter.putAll(templateRunObject.getRuntimeParameter());
            }

        }

        //取得<@function parameter...></@function>的参数
        if (MapUtils.isNotEmpty(params)) {
            Iterator paramIter = params.entrySet().iterator();
            while (paramIter.hasNext()) {
                Map.Entry ent = (Map.Entry) paramIter.next();
                if (ent.getValue() != null && !"".equals(ent.getValue().toString().trim())) {
                    parameter.put(ent.getKey().toString(), ent.getValue().toString().trim());
                }
            }
        }

        if (StringUtils.isNotBlank(referenceCode)) {
            String templatesDir = templateService.findTemplateDirCache();
            Forum forum = templateService.findForumCache(templatesDir, referenceCode);
            if (forum != null) {
                String simpleModule = StringUtils.substringBeforeLast(forum.getModule(), "_");//版块模板前缀
                //模板路径名称(env.getTemplate().getName()方法已过时)
                String templatePathName = env.getCurrentTemplate().getName();
                //模板文件名称  StringUtils.lastIndexOfIgnoreCase从后往前查，不区分大小写
                String name = templatePathName.substring(StringUtils.lastIndexOfIgnoreCase(templatePathName, "/") + 1, templatePathName.lastIndexOf("."));//删除后缀名
                if (name.equals(forum.getModule()) && forum.getInvokeMethod().equals(INVOKE_CODE.getValue())) {//1.引用代码
                    if (layoutFile.contains(forum.getLayoutFile()) || forum.getLayoutType().equals(PUBLIC_REF_VALUE_PAGE.getValue())) {
                        Object obj = templateMain.templateObject(forum, parameter, runtimeParameter);
                        env.setVariable(simpleModule, getBeansWrapper().wrap(obj));//引用代码为key  如:Product_Show_1
                        if (body != null) {
                            body.render(env.getOut());
                        }
                    }
                }
            }
        }
    }

}
